package com.blackhorse.dao;

import com.blackhorse.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 基于JdbcTemplate的DAO
 */
public class AccountDaoImplWithJdbcTemplate extends JdbcDaoSupport implements AccountDao {
    //存在问题，将来可能有多个dao，每一个dao实现类中都需要注入JdbcTemplate，存在重复代码
    //解决方法：抽取重复代码到JdbcDaoSuppert中，让所有Dao继承该类

//    private JdbcTemplate jdbcTemplate;
//
//    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
//        this.jdbcTemplate = jdbcTemplate;
//    }

    public Account findAccountById(int id) {
        String sql = "select * from account where id = ?";
        return super.getJdbcTemplate().queryForObject(sql, new BeanPropertyRowMapper<Account>(Account.class), id);
    }

    public Account findAccountByName(String name) {
        String sql = "select * from account where name = ?";
        List<Account> list = super.getJdbcTemplate().query(sql, new BeanPropertyRowMapper<Account>(Account.class), name);
        if (list.isEmpty()) {
            return null;
        } else if (list.size() == 1) {
            return list.get(0);
        } else {
            throw new RuntimeException("查询结果不唯一！");
        }
    }

    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name = ?, money = ? where id = ?",
                account.getName(), account.getMoney(), account.getId());
    }
}
